<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Provides access to the list of known viewer delegates.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
abstract class DMObjectViewerDelegateManager {

	/**
	 * @var associative array of class name => name pairs
	 */
	private static $classes = array();

	/**
	 * @param string class Class name
	 * @return string Viewer name
	 */
	public static function getNameForClass($class) {
		// constructor parameters are not important here
		$col = DMCollectionFactory::getCollection("/dmdefault");
		$obj = new DMObject($col, 1, DMDataStoreFactory::getDataStore(),
				DMConfigIni::getInstance());
		$type = new DMMediaType("animal", "cat");
		$instance = new $class($obj, $type, 500, 500);
		return $instance->getName();
	}

	/**
	 * @return associative array of class name => viewer name pairs
	 */
	private static function initializeClassArray() {
		// built-in viewers
		self::populateClassArrayWithPath(dirname(__FILE__));
		// custom viewers
		self::populateClassArrayWithPath(
				dirname(__FILE__) . "/../../extensions/viewers");
		natcasesort(self::$classes);
	}

	private static function populateClassArrayWithPath($path) {
		$it = new DirectoryIterator($path);
		foreach (new IteratorIterator($it) as $filename) {
			// skip hidden folders, such as .svn
			if (substr($filename, 0, 1) == ".") {
				continue;
			}
			if (strlen($filename) < 3) {
				continue;
			}
			if (!is_dir($path . "/" . $filename)) {
				continue;
			}
			if (!file_exists($path . "/" . $filename . "/" . $filename . ".php")) {
				continue;
			}
			$abs_path = $path . "/" . $filename . "/" . $filename . ".php";
			include_once($abs_path);
			$info = pathinfo($abs_path);
			if (array_key_exists("extension", $info)) {
				$class = basename($filename, "." . $info['extension']);
				if (interface_exists($class)) {
					continue;
				}
				$rclass = new ReflectionClass($class);
				if ($rclass->implementsInterface("DMObjectViewerDelegate")) {
					self::$classes[$class] = self::getNameForClass($class);
				}
			}
		}
	}

	/**
	 * @return array Array of the class names of all registered
	 * DMObjectViewerDelegates, as strings.
	 * @since 2.0
	 */
	public static function getAllViewerDelegateClassNames() {
		if (count(self::$classes) < 1) {
			self::initializeClassArray();
		}
		return array_keys(self::$classes);
	}

	/**
	 * @return array Array of the names of all registered
	 * DMObjectViewerDelegates, as strings.
	 * @since 2.0
	 */
	public static function getAllViewerDelegateNames() {
		if (count(self::$classes) < 1) {
			self::initializeClassArray();
		}
		return self::$classes;
	}

}
